import os
import subprocess
import threading

from tensorboardX import SummaryWriter
from multiprocessing import Pool

from utils.CommonUtils import get_current_timestamp
from utils.LogUtils import get_file_logger_loguru
from utils.Visualizer import Visualizer


class _BaseHandler(object):
    def __init__(self, config):
        self.config = config
        self.processPool = Pool(2)
        logger_save_path = os.path.join(config.basic_dir, config.run_logs_dir,
                                        get_current_timestamp() + "_" + config.name + ".txt")
        self.logger = get_file_logger_loguru(logger_save_path)
        self.visualizer = Visualizer(config)
        self.tensorBoardLogger = self.__create_tensorboard_logger__(
            os.path.join(config.basic_dir, config.tensorboard_logs_dir))
        pass

    # def __del__(self):
    #     self.processPool.close()
    #     self.processPool.join()

    def train(self):
        raise NotImplementedError

    # Todo 如何定义必须被子类实现的方法
    """
    raise NotImplementedError 是其中一种方法
    或者使用纯虚基类
    """

    def inference(self):
        raise NotImplementedError

    def __create_tensorboard_logger__(self, basic_log_dir):
        time_stamp = get_current_timestamp()
        log_dir = os.path.join(basic_log_dir, time_stamp + "_" + self.config.name)
        if not os.path.exists(log_dir):
            os.mkdir(log_dir)

        train_logs_writer = SummaryWriter(log_dir=log_dir)
        run_order = r"tensorboard --logdir=" + log_dir
        self.logger.info("The run order of tensorboard is " + run_order)

        def inner_function(inner_run_order):
            subprocess.run(inner_run_order)

        thread1 = threading.Thread(target=inner_function, kwargs={"inner_run_order": run_order})
        thread1.start()
        self.logger.info(threading.current_thread().name + ' start to run tensorboard')
        self.logger.info("Tensorboard start up...")

        return train_logs_writer
